package com.strato.mvc.api.v1_0_0.control.impl.matcher;

import com.strato.mvc.api.v1_0_0.control.PathVariable;
import com.strato.mvc.api.v1_0_0.control.PathVariableCollector;

public class PathVariableMatcher implements Matcher {

	private PathVariable pv;

	public PathVariableMatcher(PathVariable pv){
		this.pv=pv;
	}
	
	@Override
	public int match(String part, PathVariableCollector pvc) {
		PathVariable newPv=new PathVariable(pv.getName(),pv.getType());
		newPv.setValue(fromString(part,pv.getName(),pv.getType()));
		pvc.collect(newPv);
		return MATCH;
	}

	private Object fromString(String part, String varName, Class<?> type) {
		if(Integer.class.equals(type)||Integer.TYPE.equals(type)){
			try{
				return Integer.valueOf(part);
			}catch(NumberFormatException e){
				throw new IllegalArgumentException("{"+varName+"} should be a number but turned to be:"+part, e);
			}
		}else if(Long.class.equals(type)||Long.TYPE.equals(type)){
			try{
				return Long.valueOf(part);
			}catch(NumberFormatException e){
				throw new IllegalArgumentException("{"+varName+"} should be a number but turned to be:"+part, e);
			}
		}else if(String.class.equals(type)){
			return part;
		}
		throw new IllegalArgumentException("Cannot convert '"+part+"' into "+type);
	}

	@Override
	public boolean conflicts(Matcher matcher) {
		return matcher instanceof PathVariableMatcher;
	}

	@Override
	public boolean mequals(Matcher matcher) {
		if(!(matcher instanceof PathVariableMatcher)){
			return false;
		}
		PathVariableMatcher pvm=(PathVariableMatcher) matcher;
		return pvm.pv.getName().equals(this.pv.getName())&&pvm.pv.getType().equals(this.pv.getType());
	}

	public String toString(){
		return "{"+pv.getName()+":"+pv.getType().getName()+"}";
	}
}
